from PyQt6.QtWidgets import (QFrame, QVBoxLayout, QHBoxLayout, QLabel, 
                           QPushButton, QWidget, QFileDialog, QToolTip, QApplication,
                           QGraphicsDropShadowEffect)
from PyQt6.QtCore import Qt, pyqtSignal, QRectF
from PyQt6.QtGui import (QPixmap, QPainter, QColor, QLinearGradient, 
                        QFont, QPainterPath, QFontMetrics)
import time
from pathlib import Path

class BookCard(QFrame):
    """书籍卡片"""
    bookSelected = pyqtSignal(str)
    deleteRequested = pyqtSignal(str)

    def __init__(self, book, parent=None):
        try:
            super().__init__(parent)
            if not book:
                raise ValueError("书籍信息不能为空")
            
            self.book = book
            self.setObjectName("bookCard")
            self.setFixedSize(160, 250)  # 减小卡片高度，让底部更紧凑
            
            # 设置基础样式
            self.setStyleSheet(self.get_style())
            
            # 初始化UI
            self.init_ui()
            
            # 添加点击事件
            self.setCursor(Qt.CursorShape.PointingHandCursor)
            self.mousePressEvent = lambda e: self.bookSelected.emit(self.book['id'])
            
            print(f"初始化书籍卡片成功: {book.get('title', 'Unknown')}")
            
        except Exception as e:
            print(f"初始化书籍卡片失败: {str(e)}")
            raise

    def get_style(self):
        return """
            QFrame#bookCard {
                background: transparent;
                border: none;
            }
            QWidget#contentContainer {
                background: transparent;
                border: 2px solid rgba(255, 255, 255, 0.08);
                border-radius: 4px;
            }
            QWidget#contentContainer:hover {
                border: 2px solid rgba(255, 255, 255, 0.15);
            }
            QLabel#progressLabel {
                color: rgba(255, 255, 255, 0.7);
                font-size: 11px;
                background: transparent;
                padding: 0px;
                margin: 0px;
            }
            QPushButton#uploadCoverBtn {
                background: transparent;
                border: none;
                color: rgba(255, 255, 255, 0.7);
                font-size: 12px;
                padding: 0px;
                margin: 0px;
            }
            QPushButton#uploadCoverBtn:hover {
                color: rgba(255, 255, 255, 0.9);
            }
            QPushButton#deleteBtn {
                background: transparent;
                border: none;
                color: rgba(255, 255, 255, 0.7);
                font-size: 12px;
                padding: 0px;
                margin: 0px;
            }
            QPushButton#deleteBtn:hover {
                color: rgba(255, 255, 255, 0.9);
            }
            QFrame#coverFrame {
                background: transparent;
                border: none;
                margin: 0px;
                padding: 0px;
            }
            QLabel#coverLabel {
                background: transparent;
                margin: 0px;
                padding: 0px;
            }
            QWidget#titleContainer {
                background: transparent;
                border-radius: 2px;
                margin: 0px;
                padding: 0px;
                min-height: 24px;
                max-height: 24px;
            }
            QWidget#titleContainer:hover {
                background: transparent;
            }
            QLabel#titleLabel {
                color: rgba(255, 255, 255, 1);
                font-size: 15px;  /* 增大字号 */
                font-weight: bold;
                background: transparent;
                padding: 0px;
                margin: 0px;
            }
            QLabel#timeLabel {
                color: rgba(255, 255, 255, 0.5);
                font-size: 11px;
                background: transparent;
                padding: 4px 8px;
            }
        """

    def init_ui(self):
        # 主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)

        # 内容容器
        content_container = QWidget()
        content_container.setObjectName("contentContainer")
        content_layout = QVBoxLayout(content_container)
        content_layout.setContentsMargins(8, 4, 8, 4)  # 减小顶部和底部边距
        content_layout.setSpacing(2)  # 进一步减小间距

        # 顶部工具栏
        top_bar = QWidget()
        top_bar.setFixedHeight(20)  # 减小顶部工具栏高度
        top_layout = QHBoxLayout(top_bar)
        top_layout.setContentsMargins(0, 0, 0, 0)
        top_layout.setSpacing(4)
        
        # 添加封面按钮
        upload_btn = QPushButton("添加封面")
        upload_btn.setObjectName("uploadCoverBtn")
        upload_btn.clicked.connect(self.upload_cover)
        top_layout.addWidget(upload_btn, 1, Qt.AlignmentFlag.AlignCenter)
        
        # 删除按钮
        delete_btn = QPushButton("✕")
        delete_btn.setObjectName("deleteBtn")
        delete_btn.setFixedSize(20, 20)
        delete_btn.clicked.connect(lambda: self.deleteRequested.emit(self.book['id']))
        top_layout.addWidget(delete_btn)
        
        content_layout.addWidget(top_bar)

        # 封面区域
        cover_frame = QWidget()
        cover_frame.setObjectName("coverFrame")
        cover_frame.setFixedSize(144, 180)
        
        cover_layout = QVBoxLayout(cover_frame)
        cover_layout.setContentsMargins(0, 0, 0, 0)
        cover_layout.setSpacing(0)

        self.cover_label = QLabel()
        self.cover_label.setObjectName("coverLabel")
        self.cover_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.cover_label.setFixedSize(144, 180)
        cover_layout.addWidget(self.cover_label)

        # 显示封面
        if self.book.get('cover'):
            pixmap = QPixmap(self.book['cover'])
            if pixmap.isNull():
                pixmap = self.create_default_cover(144, 180)
        else:
            pixmap = self.create_default_cover(144, 180)
        
        scaled_pixmap = pixmap.scaled(
            144, 180,
            Qt.AspectRatioMode.IgnoreAspectRatio,
            Qt.TransformationMode.SmoothTransformation
        )
        self.cover_label.setPixmap(scaled_pixmap)

        # 移除封面的单独点击事件，因为整个卡片都可以点击
        # cover_frame.mousePressEvent = lambda e: self.bookSelected.emit(self.book['id'])
        content_layout.addWidget(cover_frame, 0, Qt.AlignmentFlag.AlignHCenter)

        # 标题容器
        title_container = QWidget()
        title_container.setObjectName("titleContainer")
        title_container.setFixedHeight(24)  # 调整标题高度
        title_layout = QHBoxLayout(title_container)
        title_layout.setContentsMargins(0, 0, 0, 0)
        title_layout.setSpacing(0)

        # 书名标签
        title_label = QLabel()
        title_label.setObjectName("titleLabel")
        title_label.setFixedHeight(24)
        title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)

        # 设置字体
        font = QFont('Microsoft YaHei', 15)  # 增大字号
        font.setBold(True)
        font.setWeight(QFont.Weight.ExtraBold)  # 设置更粗的字重
        title_label.setFont(font)

        # 增强描边效果
        effect = QGraphicsDropShadowEffect()
        effect.setColor(QColor(0, 0, 0))
        effect.setBlurRadius(6)  # 增加模糊半径
        effect.setOffset(0, 1)  # 保持轻微的阴影偏移
        effect.setColor(QColor(0, 0, 0, 180))  # 增加阴影不透明度
        title_label.setGraphicsEffect(effect)

        # 处理文本
        full_text = self.book['title']
        metrics = QFontMetrics(font)
        
        # 计算十个中文字符的宽度作为基准
        test_text = "测试测试测试测试测"  # 10个中文字
        base_width = metrics.horizontalAdvance(test_text)
        
        # 计算实际文本宽度
        text_width = metrics.horizontalAdvance(full_text)
        
        # 如果文本长度超过10个字符且宽度超过基准宽度，进行截断
        if len(full_text) > 10 and text_width > base_width:
            display_text = metrics.elidedText(
                full_text, 
                Qt.TextElideMode.ElideRight, 
                base_width
            )
            # 设置工具提示到标题标签上
            title_label.setToolTip(full_text)
            # 设置工具提示样式
            app = QApplication.instance()
            if app:
                app.setStyleSheet("""
                    QToolTip {
                        background-color: #2B2B2B;
                        color: white;
                        border: 1px solid #3F3F3F;
                        padding: 5px;
                        border-radius: 3px;
                        font-size: 12px;
                    }
                """)
        else:
            display_text = full_text

        title_label.setText(display_text)
        title_layout.addWidget(title_label)

        content_layout.addWidget(title_container, 0, Qt.AlignmentFlag.AlignHCenter)

        main_layout.addWidget(content_container)

        # 时间标签
        if 'last_read_time' in self.book:
            timestamp = self.book['last_read_time']
            if isinstance(timestamp, str):
                timestamp = int(timestamp)
            time_str = time.strftime("%m月%d日%H:%M", time.localtime(timestamp))
            operation = self.book.get('last_operation', '')
            time_label = QLabel(f"{operation} · {time_str}")
            time_label.setObjectName("timeLabel")
            time_label.setAlignment(Qt.AlignmentFlag.AlignRight)
            main_layout.addWidget(time_label)

    def create_default_cover(self, width, height):
        """创建默认封面"""
        pixmap = QPixmap(width, height)
        pixmap.fill(Qt.GlobalColor.transparent)
        
        painter = QPainter(pixmap)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)
        
        # 创建渐变背景
        gradient = QLinearGradient(0, 0, 0, height)
        gradient.setColorAt(0, QColor(45, 45, 45))
        gradient.setColorAt(1, QColor(25, 25, 25))
        
        # 绘制背景
        painter.fillRect(0, 0, width, height, gradient)
        
        # 绘制装饰性图案
        pen = painter.pen()
        pen.setColor(QColor(255, 255, 255, 20))
        painter.setPen(pen)
        
        # 绘制一些装饰线条
        for i in range(0, width, 20):
            painter.drawLine(i, 0, i + 10, height)
        
        # 添加书籍图标
        icon_size = min(width, height) * 0.3
        icon_rect = QRectF((width - icon_size) / 2, (height - icon_size) / 2, 
                           icon_size, icon_size)
        
        # 绘制一个简单的书本图标
        painter.setPen(Qt.PenStyle.NoPen)
        painter.setBrush(QColor(255, 255, 255, 30))
        
        path = QPainterPath()
        path.addRoundedRect(icon_rect, 5, 5)
        painter.drawPath(path)
        
        # 添加书脊
        spine_width = icon_size * 0.2
        spine_rect = QRectF(icon_rect.x() - spine_width, icon_rect.y(),
                           spine_width, icon_size)
        path = QPainterPath()
        path.addRoundedRect(spine_rect, 5, 5)
        painter.drawPath(path)
        
        painter.end()
        return pixmap

    def upload_cover(self):
        """上传封面图片"""
        file_name, _ = QFileDialog.getOpenFileName(
            self,
            "选择封面图片",
            "",
            "图片文件 (*.jpg *.jpeg *.png *.bmp)"
        )
        if file_name:
            # 更新书籍数据中的封面路径
            self.book['cover'] = file_name
            
            # 显示新封面
            pixmap = QPixmap(file_name)
            if not pixmap.isNull():
                # 使用统一的封面尺寸
                scaled_pixmap = pixmap.scaled(
                    144, 180,  # 使用固定的封面尺寸
                    Qt.AspectRatioMode.IgnoreAspectRatio,
                    Qt.TransformationMode.SmoothTransformation
                )
                self.cover_label.setPixmap(scaled_pixmap)
            
            print(f"设置封面图片: {file_name}")

    def update_cover(self, cover_path):
        """更新封面显示"""
        if cover_path and Path(cover_path).exists():
            pixmap = QPixmap(cover_path)
            if not pixmap.isNull():
                scaled_pixmap = pixmap.scaled(
                    144, 180,  # 固定封面尺寸
                    Qt.AspectRatioMode.IgnoreAspectRatio,
                    Qt.TransformationMode.SmoothTransformation
                )
                self.cover_label.setPixmap(scaled_pixmap)
        else:
            # 显示默认封面
            default_pixmap = self.create_default_cover(144, 180)
            self.cover_label.setPixmap(default_pixmap) 